﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Webcar.Entitys;
using Webcar.Utils;
namespace Webcar
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                try
                {
                    string userid = Request.Form["UserID"];
                    string pass = Request.Form["Password"];
                    if (userid.IsNull())
                    {
                        Response.Redirect("~/Account/Login");
                    }
                    else
                    {
                        CheckLogin(userid, pass);
                    }
                }
                catch(Exception ex)
                {
                    //throw;
                    string x = ex.ToString();
                    //Response.Redirect("~/Account/Login");
                    Response.Redirect(FormsAuthentication.DefaultUrl);
                }
                //UrlHelper.GenerateUrl("Default")
                //string url = "~/Account/Login?UserID={0}&Password={1}".FormatWith(userid, pass);
                //Response.Redirect(url);
            }
        }
        void CheckLogin(string user, string pass)
        {
            var exist_user = WebcarDataProvider.DB.v_all_users.FirstOrDefault(a => a.account == user || a.cn == user);
            if (exist_user == null)
            {
                throw new Exception("你输入的用户" + user + "不存在");
            }
            if (pass.MD5Hash().NotIn(exist_user.password, exist_user.oldpass) && pass.NotIn(exist_user.password, exist_user.oldpass))
            {
                throw new Exception("密码错误。");
            }
            FormsAuthentication.SetAuthCookie(exist_user.account, true);
            Response.Redirect(FormsAuthentication.DefaultUrl,true);
        }

        protected void Button1_Click(object sender, EventArgs e)
        {

        }
    }
}